package com.yy.ant.sys.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.yy.ant.sys.entity.Resources;
import com.yy.ant.sys.entity.RoleResources;
import com.yy.ant.sys.entity.UserRole;
import com.yy.ant.sys.service.*;
import com.yy.utils.JwtUtils;
import com.yy.utils.SystemConstant;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yy.ant.sys.entity.User;
import com.yy.model.ResultMsg;
import com.yy.model.ResultTable;
import com.yy.model.enums.ResultEnum;
import com.yy.utils.Base64Util;
import com.yy.utils.SessionUtil;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author liyingying
 * @since 2019-12-20
 */
@RestController
@RequestMapping("/sys/user")
public class UserController {

	@Autowired
	private IUserService iUserService;

	@Autowired
	private IResourcesService iResourcesService;

	@Autowired
	private IUserRoleService iUserRoleService;

	@Autowired
	private IRoleResourcesService iRoleResourcesService;
	@Value("${yy.touxiang}")
	private String url;
	/**
	 * 登录
	 *
	 * @return
	 */
	@RequestMapping(value = "/login")
	public JSONObject login(@RequestParam(value = "name", required = false) String name,
			@RequestParam(value = "pass") String pass) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("token", "");

		try {
			User user = iUserService.getOne(
					new QueryWrapper<User>().eq("uname", name).eq("upass", Base64Util.encode(pass)),true);
			String JWT = JwtUtils.createJWT(user.getId().toString(), name, SystemConstant.JWT_TTL);
			List<String> listr=new ArrayList<>();
			jsonObject.put("token", JWT);
			jsonObject.put("id", user.getId());
			jsonObject.put("name", user.getUname());
			jsonObject.put("names", user.getUsername());
			jsonObject.put("code", 0);
			jsonObject.put("success", true);

			jsonObject.put("msg", "登录成功");
			if (SessionUtil.getAdmin(name)) {
				//查询按钮
				List<Resources> list=iResourcesService.list(new QueryWrapper<Resources>().eq("types",1));
				for(Resources o:list){
					listr.add(o.getIdentification());
				}
			}else {
				//根据用户权限查询按钮
				List<Long> list=new ArrayList<>();
				List<UserRole> userRoles=iUserRoleService.list(new QueryWrapper<UserRole>().eq("user_id",user.getId()));
				for (UserRole userRole:userRoles){
					list.add(userRole.getRoleId());
				}
				List<Long> list1=new ArrayList<>();
				if (list!=null&&list.size()>0){
					List<RoleResources> roleResources=iRoleResourcesService.list(new QueryWrapper<RoleResources>().in("role_id",list));
					for (RoleResources o:roleResources){
						list1.add(o.getResourcesId());
					}
				}
				if (list1!=null&&list1.size()>0){
					List<Resources> lists=iResourcesService.list(new QueryWrapper<Resources>().in("id",list1).eq("types",1));
					for(Resources o:lists){
						listr.add(o.getIdentification());
					}
				}
			}
			jsonObject.put("power", listr);
		} catch (Exception e) {
            jsonObject.put("msg", "密码错误");
        }
		return jsonObject;
	}

	/**
	 * 根据用户ID 初始化数据
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getInitData")
	public ResultMsg getInitData(@RequestParam(value = "id", required = false) String id){
		ResultMsg resultMsg=iUserService.getInitData(id,url);
	//	System.out.println(JSON.toJSONString(resultMsg));
		return resultMsg;
	}
	
	
	
	/**
	 * 根据用户ID 查询数据
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/getById")
	public ResultMsg getById(@RequestParam(value = "id", required = false) String id){
		User user=iUserService.getById(id);
		ResultMsg resultMsg=new ResultMsg();
		resultMsg.setData(user);
		return resultMsg;
	}
	/**
	 * 分页查询
	 * 
	 * @param str
	 * @param page
	 * @param limit
	 * @return
	 */
	@RequestMapping(value = "/listPage")
	public ResultTable<User> listPage(@RequestParam(value = "str", required = false) String str,
			@RequestParam(value = "page") String page, @RequestParam(value = "limit") String limit) {
		// System.out.println(str);
		JSONObject jsonObject = JSONObject.parseObject(str);
		QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
		if (jsonObject != null) {
			if (StringUtils.isNotEmpty(jsonObject.getString("startTime"))
					&& StringUtils.isNotEmpty(jsonObject.getString("endTime"))) {
				queryWrapper.between("createtime", jsonObject.getString("startTime"), jsonObject.getString("endTime"));
			}
			if (StringUtils.isNotEmpty(jsonObject.getString("username"))) {
				queryWrapper.like("username", jsonObject.getString("username"));
			}
		}

		IPage<User> iPage = iUserService.page(new Page<>(Integer.valueOf(page), Integer.valueOf(limit)), queryWrapper);
		ResultTable<User> uResultTable = new ResultTable<User>();
		uResultTable.setCount(iPage.getTotal());
		List<User> sUsers = iPage.getRecords();
		List<User> lUsers = new ArrayList<User>();
		for (User o : sUsers) {
			o.setUpass(Base64Util.decode(o.getUpass()));
			lUsers.add(o);
		}
		uResultTable.setData(lUsers);
		return uResultTable;
	}

	/**
	 * 全部查询
	 * 
	 * @return
	 */
	@RequestMapping(value = "/listAll")
	public List<User> listall() {
		List<User> list = iUserService.list();
		return list;
	}

	/**
	 * 新增
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/add")
	public ResultMsg add(@RequestParam(value = "str", required = false) String str) {
		ResultMsg resultMsg = new ResultMsg();
		User user = JSON.parseObject(str, User.class);

		user.setCreatetime(new Date());
		if (StringUtils.isNotEmpty(user.getUpass())) {
			user.setUpass(Base64Util.encode(user.getUpass()));
		}
		user.setStatus("offline");
		boolean b = iUserService.save(user);
		if (b) {
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_create_failed.getMsg());
		} else {
			resultMsg.setMsg(ResultEnum.error_create_failed.getMsg());
		}

		return resultMsg;
	}

	/**
	 * 注册
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/register")
	public ResultMsg register(@RequestParam(value = "str", required = false) String str) {
		User user = JSON.parseObject(str, User.class);
		user.setCreatetime(new Date());
		if (StringUtils.isNotEmpty(user.getUpass())) {
			user.setUpass(Base64Util.encode(user.getUpass()));
		}
		ResultMsg resultMsg = new ResultMsg();
		user.setStatus("offline");
		boolean b = iUserService.save(user);
		if (b) {
			//默认创建一个分组好友
			iUserService.setGroupFlock(user);
			UserRole userRole=new UserRole();
			userRole.setRoleId(1L);
			userRole.setUserId(user.getId());
			iUserRoleService.save(userRole);
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_create_failed.getMsg());
		} else {
			resultMsg.setMsg(ResultEnum.error_create_failed.getMsg());
		}

		return resultMsg;
	}
	
	/**
	 * 删除
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/delete")
	public ResultMsg delete(@RequestParam(value = "str", required = false) String str) {
		List<Long> ids = new ArrayList<>();
		String[] id = str.split(",");
		for (int i = 0; i < id.length; i++) {
			if (StringUtils.isNotEmpty(id[i])) {
				ids.add(Long.valueOf(id[i]));
			}
		}
		ResultMsg resultMsg = new ResultMsg();
		boolean b = iUserService.removeByIds(ids);
		if (b) {
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_delete_failed.getMsg());
		} else {
			resultMsg.setMsg(ResultEnum.error_delete_failed.getMsg());
		}
		return resultMsg;
	}

	@RequestMapping(value = "/getbyId")
	public ResultMsg ById(@RequestParam(value = "id", required = false) String id) {
		ResultMsg resultMsg = new ResultMsg();
		User user =iUserService.getById(id);
		user.setUpass("");
		resultMsg.setData(user);
		return resultMsg;
	}

	/**
	 * 修改
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/update")
	public ResultMsg update(@RequestHeader("token") String token, @RequestParam(value = "str", required = false) String str) {
		ResultMsg resultMsg = new ResultMsg();
		User user = JSON.parseObject(str, User.class);
		ResultMsg resultMsg1=JwtUtils.validateJWT(token);
		if (!resultMsg1.isSuccess()){
			return resultMsg1;
		}
		Claims claims= (Claims) resultMsg1.getData();
		User sysUser = iUserService.getById(claims.getId());
		if (SessionUtil.getAdmin(user.getUname())&&!SessionUtil.getAdmin(sysUser.getUname())){
			resultMsg.setMsg(ResultEnum.ERROR_USUR_C.getMsg());
			return resultMsg;
		}else {
			if (StringUtils.isNotEmpty(user.getUpass())) {
				user.setUpass(Base64Util.encode(user.getUpass()));
			}
			boolean b = iUserService.updateById(user);
			if (b) {
				resultMsg.setSuccess(true);
				resultMsg.setMsg(ResultEnum.sucess_update_failed.getMsg());
			} else {
				resultMsg.setMsg(ResultEnum.error_update_failed.getMsg());
			}
		}

		return resultMsg;
	}

	/**
	 * 批量停用
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/normal")
	public ResultMsg normal(@RequestParam(value = "str", required = false) String str) {
		List<User> list = new ArrayList<User>();
		String[] id = str.split(",");
		for (int i = 0; i < id.length; i++) {
			if (StringUtils.isNotEmpty(id[i])) {
				User user = new User();
				user.setId(Long.valueOf(id[i]));
				user.setStates(0);
				list.add(user);
			}
		}

		ResultMsg resultMsg = new ResultMsg();
		boolean b = iUserService.updateBatchById(list);
		if (b) {
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_update_failed.getMsg());
		} else {
			resultMsg.setMsg(ResultEnum.error_update_failed.getMsg());
		}
		return resultMsg;
	}

	/**
	 * 批量停用
	 * 
	 * @param str
	 * @return
	 */
	@RequestMapping(value = "/stop")
	public ResultMsg stop(@RequestParam(value = "str", required = false) String str) {
		List<User> list = new ArrayList<User>();
		String[] id = str.split(",");
		for (int i = 0; i < id.length; i++) {
			if (StringUtils.isNotEmpty(id[i])) {
				User user = new User();
				user.setId(Long.valueOf(id[i]));
				user.setStates(1);
				list.add(user);
			}
		}

		ResultMsg resultMsg = new ResultMsg();
		boolean b = iUserService.updateBatchById(list);
		if (b) {
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_update_failed.getMsg());
		} else {
			resultMsg.setMsg(ResultEnum.error_update_failed.getMsg());
		}
		return resultMsg;
	}

	/**
	 * 切换在线离线状态
	 * @return
	 */
	@RequestMapping(value = "/setStates")
	public ResultMsg setStates(@RequestHeader("token") String token,@RequestParam(value = "states", required = false) String states){
		ResultMsg resultMsg1=JwtUtils.validateJWT(token);
		if (!resultMsg1.isSuccess()){
			return resultMsg1;
		}
		Claims claims= (Claims) resultMsg1.getData();
		User user = new User();
		user.setId(Long.valueOf(claims.getId()));
		user.setStatus(states);
		iUserService.updateById(user);
		ResultMsg resultMsg = new ResultMsg();
		return resultMsg;
	}
	/**
	 * 保存签名
	 * @return
	 */
	@RequestMapping(value = "/setSign")
	public ResultMsg setSign(@RequestHeader("token") String token,@RequestParam(value = "sign", required = false) String sign){
		ResultMsg resultMsg1=JwtUtils.validateJWT(token);
		if (!resultMsg1.isSuccess()){
			return resultMsg1;
		}
		Claims claims= (Claims) resultMsg1.getData();
		User user = new User();
		user.setId(Long.valueOf(claims.getId()));
		user.setSign(sign);
		iUserService.updateById(user);
		ResultMsg resultMsg = new ResultMsg();
		return resultMsg;
	}
	
}
